import * as Cesium from "cesium";
import { CoordTransform } from './coordTransform';

export default class AMapGeocoderService {
    constructor(options) {
        if (Cesium.defined(options) && Cesium.defined(options.key)) {
            this.key = options.key;
        } else {
            console.error("key不能为空");
        }
    }

    async geocode(input) {
        const regex = /([-+]?\d{1,3}(?:\.\d+)?),\s*([-+]?\d{1,3}(?:\.\d+)?)/;

        try {
            if (input.match(regex)) {
                // 地理逆编码
                const endpoint = 'https://restapi.amap.com/v3/geocode/regeo?';
                const parts = input.split(',');
                // 将WGS84坐标转换为高德坐标
                const GCJ02 = CoordTransform.WGS84ToGCJ02(Number(parts[0].trim()), Number(parts[1].trim()));
                const query = `location=${GCJ02[0]},${GCJ02[1]}&key=${this.key}&output=json`;
                const response = await Cesium.Resource.fetchJsonp(endpoint + query);
                const address = response.regeocode.formatted_address;
                return {
                    displayName: !Array.isArray(address) ? address : input,
                    destination: Cesium.Cartesian3.fromDegrees(Number(parts[0].trim()), Number(parts[1].trim()))
                };
            } else {

                // 关键字搜索
                // let endpoint = 'https://restapi.amap.com/v3/place/text?';
                // let query = `keywords=${input}&key=${this.key}&offset=5&output=json`;
                // let requestString = endpoint + query;

                // 使用Cesium的jsonp方法获取数据
                // return Cesium.Resource.fetchJsonp(requestString).then(function (response) {
                //     let results = response.pois.map(function (poi) {
                //         // 将高德坐标转换为WGS84坐标
                //         let location = poi.location.split(',');
                //         return {
                //             displayName: poi.name + "-" + poi.address,
                //             destination: Cesium.Cartesian3.fromDegrees(Number(location[0].trim()), Number(location[1].trim()))
                //         };
                //     });
                //     return results;
                // });

                // 地理编码
                const endpoint = 'https://restapi.amap.com/v3/geocode/geo?';
                const query = `address=${input}&key=${this.key}&output=json`;
                const response = await Cesium.Resource.fetchJsonp(endpoint + query);

                if (response.status === '0') return [];
                
                return response.geocodes.map(poi => {
                    const location = poi.location.split(',');
                    // 将高德坐标转换为WGS84坐标
                    const WGS84 = CoordTransform.GCJ02ToWGS84(Number(location[0].trim()), Number(location[1].trim()));
                    return {
                        displayName: poi.formatted_address,
                        destination: Cesium.Cartesian3.fromDegrees(WGS84[0], WGS84[1])
                    };
                });
            }
        } catch (error) {
            console.error('Geocoding error:', error);
            return [];
        }
    }
}